<template>
  <div class="product-description">
    <h3>填写商品描述</h3>
    <p class="tip">使用富文本编辑器编写商品详细描述</p>
    
    <div class="editor-container">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button-group>
          <el-button size="small" @click="insertHTML('bold')"><b>B</b></el-button>
          <el-button size="small" @click="insertHTML('italic')"><i>I</i></el-button>
          <el-button size="small" @click="insertHTML('underline')"><u>U</u></el-button>
        </el-button-group>
        
        <el-button-group style="margin-left: 10px;">
          <el-button size="small" @click="insertHTML('formatBlock', 'h1')">H1</el-button>
          <el-button size="small" @click="insertHTML('formatBlock', 'h2')">H2</el-button>
          <el-button size="small" @click="insertHTML('formatBlock', 'p')">P</el-button>
        </el-button-group>

        <el-button-group style="margin-left: 10px;">
          <el-button size="small" @click="insertHTML('insertUnorderedList')">
            <el-icon><List /></el-icon>
          </el-button>
          <el-button size="small" @click="insertHTML('insertOrderedList')">
            <el-icon><Memo /></el-icon>
          </el-button>
        </el-button-group>

        <el-upload
          action="#"
          :show-file-list="false"
          :before-upload="beforeImageUpload"
          :on-change="handleImageUpload"
          accept="image/*"
          style="display: inline-block; margin-left: 10px;"
        >
          <el-button size="small">
            <el-icon><Picture /></el-icon>
            插入图片
          </el-button>
        </el-upload>

        <el-button size="small" style="margin-left: 10px;" @click="toggleHTML">
          {{ showHTML ? '可视化' : 'HTML' }}
        </el-button>
      </div>

      <!-- 编辑区域 -->
      <div v-show="!showHTML" class="editor-content">
        <div
          ref="editorRef"
          class="editor"
          :class="{ 'is-dragging': isDragging }"
          contenteditable="true"
          @input="handleInput"
          @paste="handlePaste"
          @drop="handleDrop"
          @dragover="handleDragOver"
          @dragleave="handleDragLeave"
        ></div>
      </div>

      <!-- HTML源码 -->
      <div v-show="showHTML" class="html-content">
        <el-input
          v-model="htmlContent"
          type="textarea"
          :rows="20"
          @input="handleHTMLInput"
        />
      </div>
    </div>

    <!-- 预览区域 -->
    <div class="preview-section">
      <div class="section-title">预览效果</div>
      <div class="preview-content" v-html="content"></div>
    </div>
  </div>
</template>

<script>
import { ref, watch } from 'vue'
import { List, Memo, Picture } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'ProductDescription',
  components: {
    List,
    Memo,
    Picture
  },
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const editorRef = ref()
    const content = ref('')
    const htmlContent = ref('')
    const showHTML = ref(false)
    const isDragging = ref(false)

    // 监听props变化
    watch(() => props.modelValue, (newVal) => {
      content.value = newVal
      htmlContent.value = newVal
      if (editorRef.value && editorRef.value.innerHTML !== newVal) {
        editorRef.value.innerHTML = newVal
      }
    }, { immediate: true })

    // 插入HTML
    const insertHTML = (command, value = null) => {
      document.execCommand(command, false, value)
      updateContent()
    }

    // 输入处理
    const handleInput = () => {
      updateContent()
    }

    // 粘贴处理
    const handlePaste = (e) => {
      e.preventDefault()
      
      // 获取粘贴的文件（图片）
      const items = e.clipboardData.items
      let hasImage = false
      let imageCount = 0
      
      for (let i = 0; i < items.length; i++) {
        const item = items[i]
        if (item.type.indexOf('image') !== -1) {
          hasImage = true
          imageCount++
          const file = item.getAsFile()
          insertImageFromFile(file)
        }
      }
      
      // 显示上传提示
      if (imageCount > 0) {
        ElMessage.success(`正在插入 ${imageCount} 张图片...`)
      }
      
      // 如果没有图片，处理文本
      if (!hasImage) {
        const text = e.clipboardData.getData('text/plain')
        document.execCommand('insertText', false, text)
      }
    }

    // 拖拽放置处理
    const handleDrop = (e) => {
      e.preventDefault()
      isDragging.value = false
      const files = e.dataTransfer.files
      
      if (files && files.length > 0) {
        let imageCount = 0
        for (let i = 0; i < files.length; i++) {
          const file = files[i]
          if (file.type.startsWith('image/')) {
            imageCount++
            insertImageFromFile(file)
          }
        }
        
        if (imageCount > 0) {
          ElMessage.success(`正在插入 ${imageCount} 张图片...`)
        } else {
          ElMessage.warning('请拖拽图片文件')
        }
      }
    }

    // 拖拽悬停处理
    const handleDragOver = (e) => {
      e.preventDefault()
      isDragging.value = true
    }

    // 拖拽离开处理
    const handleDragLeave = (e) => {
      e.preventDefault()
      isDragging.value = false
    }

    // 从文件插入图片
    const insertImageFromFile = (file) => {
      // 验证图片大小
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return
      }
      
      const reader = new FileReader()
      reader.onload = (e) => {
        const img = `<img src="${e.target.result}" style="max-width: 100%; height: auto;" />`
        if (editorRef.value) {
          // 保存当前光标位置
          const selection = window.getSelection()
          if (selection.rangeCount > 0) {
            const range = selection.getRangeAt(0)
            const imgElement = document.createElement('div')
            imgElement.innerHTML = img
            range.insertNode(imgElement.firstChild)
            
            // 移动光标到图片后面
            range.setStartAfter(imgElement.firstChild)
            range.collapse(true)
            selection.removeAllRanges()
            selection.addRange(range)
          } else {
            document.execCommand('insertHTML', false, img)
          }
          updateContent()
        }
      }
      reader.readAsDataURL(file)
    }

    // 更新内容
    const updateContent = () => {
      if (editorRef.value) {
        content.value = editorRef.value.innerHTML
        htmlContent.value = editorRef.value.innerHTML
        emit('update:modelValue', content.value)
      }
    }

    // HTML输入处理
    const handleHTMLInput = () => {
      content.value = htmlContent.value
      if (editorRef.value) {
        editorRef.value.innerHTML = htmlContent.value
      }
      emit('update:modelValue', content.value)
    }

    // 切换HTML视图
    const toggleHTML = () => {
      showHTML.value = !showHTML.value
      if (!showHTML.value && editorRef.value) {
        editorRef.value.innerHTML = htmlContent.value
      }
    }

    // 图片上传前验证
    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    }

    // 处理图片上传
    const handleImageUpload = (file) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        const img = `<img src="${e.target.result}" style="max-width: 100%; height: auto;" />`
        if (editorRef.value) {
          document.execCommand('insertHTML', false, img)
          updateContent()
        }
      }
      reader.readAsDataURL(file.raw)
    }

    return {
      editorRef,
      content,
      htmlContent,
      showHTML,
      isDragging,
      insertHTML,
      handleInput,
      handlePaste,
      handleDrop,
      handleDragOver,
      handleDragLeave,
      handleHTMLInput,
      toggleHTML,
      beforeImageUpload,
      handleImageUpload
    }
  }
}
</script>

<style scoped>
.product-description {
  padding: 20px;
}

.product-description h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #303133;
}

.tip {
  margin: 0 0 20px 0;
  color: #909399;
  font-size: 14px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 30px;
}

.toolbar {
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}

.editor-content {
  background-color: #fff;
}

.editor {
  min-height: 400px;
  padding: 15px;
  outline: none;
  line-height: 1.6;
  position: relative;
  transition: all 0.3s;
}

.editor.is-dragging {
  background-color: #f0f9ff;
  border: 2px dashed #409eff;
}

.editor.is-dragging::after {
  content: '释放以插入图片';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  color: #409eff;
  pointer-events: none;
  z-index: 1;
}

.editor:empty:before {
  content: '请输入商品描述内容...或直接粘贴/拖拽图片';
  color: #c0c4cc;
}

.html-content {
  padding: 15px;
  background-color: #fff;
}

.preview-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
}

.preview-content {
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  min-height: 200px;
  line-height: 1.6;
}

.preview-content :deep(img) {
  max-width: 100%;
  height: auto;
}

.preview-content :deep(h1) {
  font-size: 24px;
  margin: 20px 0 10px;
}

.preview-content :deep(h2) {
  font-size: 20px;
  margin: 18px 0 10px;
}

.preview-content :deep(p) {
  margin: 10px 0;
}

.preview-content :deep(ul),
.preview-content :deep(ol) {
  margin: 10px 0;
  padding-left: 30px;
}
</style>
